package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadLocal.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {


    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 加载文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.参数校验
        if(dto.getArticleId()==null || dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不完整,不可以操作");
        }

        //2.判断是否是游客身份或者登录用户
        ApUser apUser = ApUserThreadLocalUtil.getApUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = apUser.getId();
        if(userId==0){
            //2.1 如果是游客，则不可以执行以下操作，终止
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //3如果是登录用户的话，则展示是否关注过作者，是否点赞过，是否不喜欢，是否收藏

            //是否关注过
        String followKey="USER_FOLLOW_"+userId;
        Boolean followFlag = redisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());

            //是否点赞过
        String likeKey="USER_LIKES_"+dto.getArticleId();
        Boolean likeFlag = redisTemplate.opsForHash().hasKey(likeKey, userId.toString());

            //是否不喜欢
        String unlikeKey="USER_UNLIKES_"+dto.getArticleId();
        Boolean unlikeFlag = redisTemplate.opsForHash().hasKey(unlikeKey, userId.toString());
            //是否收藏
        String collectionKey="USER_COLLECTION_"+dto.getArticleId();
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collectionKey, userId.toString());

        //5封装数据返回
        Map map=new HashMap<>();
        map.put("islike",likeFlag);
        map.put("isunlike",unlikeFlag);
        map.put("iscollection",collectionFlag);
        map.put("isfollow",followFlag);

        return ResponseResult.okResult(map);
    }
}
